//
//  LGTBaseWebVC.swift
//  KJLGT
//
//  Created by jenkin on 2019/8/13.
//  Copyright © 2019年 jenkin. All rights reserved.
//

import UIKit
import WebKit


class LGTBaseWebVC: LGTBaseVC, WKNavigationDelegate, WKUIDelegate{

    var url:String?
    var webView:WKWebView?
    var firstLoadState:Bool? = false
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setBlock()
        self.loadUrl(urlStr: self.url ?? "")
        self.webView?.addObserver(self, forKeyPath: "title", options: .new, context: nil)
        self.webView?.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
    }
    
    func setBlock(){
        weak var weakSelf = self
        self.reloadBlock = {() in
            weakSelf?.loadUrl(urlStr: self.url ?? "")
        }
    }
    
    deinit {
        self.closeLoading()
        self.webView?.removeObserver(self, forKeyPath: "title")
        self.webView?.removeObserver(self, forKeyPath: "estimatedProgress")
    }
    
    override func setUI() {
        super.setUI()
        
        self.setBavBarStyle(navBarHiden: false, title: "", back: true)
        
        self.webView = WKWebView.init(frame: CGRect.init(x:CGFloat(0), y: CGFloat(NavBarH()), width: KScreenW, height: KScreenH - CGFloat(NavBarH())))
        self.webView?.uiDelegate = self
        self.webView?.navigationDelegate = self
        self.view.addSubview(self.webView!)
        self.view.bringSubviewToFront(self.navBar)
    }
    
    func loadUrl(urlStr:String){
        let url:URL? = URL.init(string: urlStr)
        var request:URLRequest = URLRequest.init(url: url!)
        //添加cookie
        let cookieStr1:String = BaseUtil.baseUtil.getCookie(url: urlStr, type: 1)
        request.addValue(cookieStr1, forHTTPHeaderField: "Cookie")
        
        //第二种添加cookie方式
        let cookieStr2:String = BaseUtil.baseUtil.getCookie(url: urlStr, type: 2)
        let cookieScript:WKUserScript = WKUserScript.init(source: cookieStr2, injectionTime: WKUserScriptInjectionTime.atDocumentStart, forMainFrameOnly: false)
        self.webView?.configuration.userContentController.addUserScript(cookieScript)
        
        if url != nil{
            self.webView?.load(request)
            self.showLoading(loadingType: .NavLoadingType)
        }
    }
    
    //页面加载失败时调用
    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
        if self.firstLoadState == false{
            //显示加载异常视图
            self.showNoData(image: Net_NoData_Image, text: Net_Error_Text, subText: Net_Reload_Text)
        }
        self.closeLoading()
    }
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        self.firstLoadState = true
        //隐藏加载视图异常
        self.closeLoading()
    }
    
    //添加观察者方法
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
        //设置进度条
//        if keyPath == "estimatedProgress"{
//            progressView.alpha = 1.0
//            progressView.setProgress(Float(webView.estimatedProgress), animated: true)
//            if webView.estimatedProgress >= 1.0 {
//                UIView.animate(withDuration: 0.3, delay: 0.1, options: .curveEaseOut, animations: {
//                    self.progressView.alpha = 0
//                }, completion: { (finish) in
//                    self.progressView.setProgress(0.0, animated: false)
//                })
//            }
//        }
        
        //重设标题
        if keyPath == "title" {
            self.navTitleLabel?.text = self.webView?.title
        }
    }
    
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        let url =  navigationAction.request.url
        let urlStr = url?.absoluteString ?? ""
        
        if LGTViewUtil.share.commenUrl(url: urlStr) == true{
            LGTViewUtil.share.gotoVC(nav: self.navigationController!, currentVC: self, urlStr: urlStr)
            decisionHandler(WKNavigationActionPolicy.cancel)
            return
        }
        
        if urlStr.hasPrefix("https://itunes.apple.com"){
            decisionHandler(WKNavigationActionPolicy.cancel)
            let gotoURL:URL? = URL.init(string: urlStr)
            if gotoURL != nil{
                UIApplication.shared.open(gotoURL!, options: [:], completionHandler: nil)
            }
            return
        }
        decisionHandler(WKNavigationActionPolicy.allow)
    }
}
